from PySide6.QtCore import Qt, Signal
from qfluentwidgets import SettingCard, FluentIconBase
from qfluentwidgetspro import MultiSelectionComboBox
from app.common.config import cfg


class MultiSelectionComboBoxSettingCard(SettingCard):
    """多选下拉框设置卡片"""

    valueChanged = Signal(list)

    def __init__(
        self,
        icon: FluentIconBase,
        title: str,
        content: str,
        configItem,
        items: list = None,
        parent=None,
    ):
        """
        Parameters
        ----------
        icon: FluentIconBase
            卡片图标
        title: str
            卡片标题
        content: str
            卡片描述文本
        configItem: ConfigItem
            配置项
        items: list
            下拉框选项列表
        parent: QWidget
            父组件
        """
        super().__init__(icon, title, content, parent)
        self.configItem = configItem
        self.items = items
        # 创建多选下拉框
        self.comboBox = MultiSelectionComboBox(self)
        self.comboBox.setMinimumWidth(450)

        # 添加选项
        if items:
            for item in items:
                self.comboBox.addItem(item)

        # 设置当前选中项
        if isinstance(self.configItem.value, list):
            # 找到每个值对应的索引
            for value in self.configItem.value:
                for i in range(self.comboBox.count()):
                    if self.comboBox.itemText(i) == value:
                        self.comboBox.addSelectedIndex(i, emit=False)

        # 将下拉框添加到右侧
        self.hBoxLayout.addWidget(self.comboBox, 0, Qt.AlignRight)
        self.comboBox.selectedIndexesChanged.connect(self._onValueChanged)

    def _onValueChanged(self):
        """值改变时的处理"""
        # 获取选中的文本列表
        selected_texts = self.comboBox.selectedTexts()
        self.configItem.value = selected_texts
        cfg.save()
        self.valueChanged.emit(selected_texts)

    def getValue(self) -> list:
        """获取当前选中的值列表"""
        return self.comboBox.selectedTexts()

    def setValue(self, items: list):
        """设置选中的值"""
        self.comboBox.clearSelectedIndexes()
        for value in items:
            for i in range(self.comboBox.count()):
                if self.comboBox.itemText(i) == value:
                    self.comboBox.addSelectedIndex(i)

    def addItems(self, items: list):
        """添加选项"""
        for item in items:
            self.comboBox.addItem(item)

    def clear(self):
        """清空所有选项"""
        self.comboBox.clear()
